//
//  IssueView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 14..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "IssueView.h"
#import "AppDelegate.h"

@implementation IssueView
@synthesize mTableView;
@synthesize currentHeadIndex, currentPage;
@synthesize responseData, itemArray, itemHeadArray, imageURL;
@synthesize finishLoad;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        mRect = frame;
        
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
        self.responseData = [NSMutableData data];
        self.backgroundColor = ColorFromRGB(0x413c43);
        
        itemArray = [[NSMutableArray alloc] init];
        itemHeadArray = [[NSMutableArray alloc] init];
        
        self.currentHeadIndex = 0;
        
        //네트워크
        [self requestIssueListWithPageNumber:1];
        
        
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    
    mTableView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
}


#pragma mark - 생성
-(void)makeObject{
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, mRect.size.width, mRect.size.height)];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:mTableView];
    
    topMoveButton = [[UIButton alloc] initWithFrame:CGRectMake(mySize.width-10-35, mRect.size.height-44-10-35, 35, 35)];
    [topMoveButton setImage:[UIImage imageNamed:@"btn_top"] forState:UIControlStateNormal];
    [topMoveButton addTarget:self action:@selector(topMoveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:topMoveButton];
    
    
    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - mTableView.bounds.size.height, mTableView.frame.size.width, mTableView.bounds.size.height)];
    _refreshHeaderView.delegate = self;
    [mTableView addSubview:_refreshHeaderView];
    [_refreshHeaderView refreshLastUpdatedDate];
    
    [self makeActivityIndicatorView];
}

-(void)makeActivityIndicatorView{
    activieiBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mTableView.frame.size.width, 50)];
    activieiBGView.backgroundColor = ColorFromRGB(0x4d4d57);
    
    activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityView.center = CGPointMake(mTableView.frame.size.width*0.5f, 25);
    [activieiBGView addSubview:activityView];

}

#pragma mark - 위로가기
-(void)topMoveButtonAction:(id)sender{
    [mTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - 베너 숨기기
-(void)bannerHidden:(BOOL)hidden{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:hidden];
    topMoveButton.hidden = hidden;
}

#pragma mark - 네트워크 팝업
-(void)networkErrorViewReloadClick:(NetworkErrorView *)nErrorView andURLstr:(NSString *)urlStr{
    
    [self requestURL:urlStr];
    [self requestIssueListWithPageNumber:currentPage];
}

#pragma mark - 스크롤잡기

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mTableView];
	
}

#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


#pragma mark - 네트워크

-(void)requestIssueListWithPageNumber:(NSInteger)pageNumber{
    
    if (pageNumber == 1) {
        [self.itemArray removeAllObjects];
    }else{
        [activityView startAnimating];
    }
    self.currentPage = pageNumber;
    
    NSString *dataStr = [NSString stringWithFormat:@"status=0&lang=%@&page=%ld&pagesize=100",appDelegate.currentLanguage,(long)pageNumber];
    NSLog(@"requestIssueListWithPageNumber : %@",dataStr);
    dataStr = [appDelegate encryptDataURLString:dataStr];
//    NSString *url = [NSString stringWithFormat:@"%@?status=0&lang=%@&page=%ld",URL_ISSUES,appDelegate.currentLanguage,(long)pageNumber];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_ISSUES,dataStr];    //암호화
    
    [self requestURL:url];
}

-(void)requestURL:(NSString*)url{
    if ([appDelegate connectedToNetwork]) {
        
        [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
    }else{
        NetworkErrorView *nEView = [[NetworkErrorView alloc] initWithFrame:CGRectMake(0, 0, mRect.size.width, mRect.size.height)];
        nEView.networkURL = url;
        [self addSubview:nEView];
    }
    
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"이슈리스트 네트워크 요청 : %@",url);
            }
            
        }
    }
}


#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    duringNetwork = NO;
    [activityView stopAnimating];
    
    [self bannerHidden:NO];
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    self.imageURL = ([appDelegate checkObject:[resultDictionary objectForKey:@"imgurl"]]) ? [resultDictionary objectForKey:@"imgurl"] : nil;
    NSLog(@"이슈리스트 : %@",resultDictionary);
    
    NSString *currentRequestString = [NSString stringWithFormat:@"%@",connectio.currentRequest];
    NSLog(@"currentRequestString : %@",currentRequestString);
    
    
    if ([resultDictionary objectForKey:@"return_code"]) {
        if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
            currentPage++;  //담번에 부를 페이지 +1
            
            resultDictionary = [resultDictionary objectForKey:@"data"];
            
            //다음페이지가 있는지 확인
            isEnd = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;
            NSArray *items = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
            NSArray *headItems = ([appDelegate checkObject:[resultDictionary objectForKey:@"items_head"]]) ? [resultDictionary objectForKey:@"items_head"] : nil;
            
            if (items) {
                [self.itemArray addObjectsFromArray:items];
            }
            if (headItems) {
                if ([headItems count]) {
                    [self.itemHeadArray removeAllObjects];
                    [self.itemHeadArray addObjectsFromArray:headItems];
                }
            }
            
            NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
            [notification postNotificationName:ITEM_LIST_LOAD object:self.itemArray];
            
            [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5f];
            
            if (!mTableView) {
                
                [self makeObject];
            }
            [mTableView reloadData];
            
            
            
            self.finishLoad = YES;
            
            ViewController *vController = (ViewController*)appDelegate.window.rootViewController;
            if (vController.introView &&vController.finishedAnimation) {
                if ([vController.introView superview]) {
                    [vController introAnimationEnd];
                }
            }
            
            if (languagesKorean) {
                
                //띠베너 갱신
                [vController requestManSDK];
            }
        }
    }
    
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    [self bannerHidden:NO];
    [activityView stopAnimating];
    
    NSLog(@"이슈리스트 네트워크 요청 실패 : %@",error);
    ViewController *vController = (ViewController*)appDelegate.window.rootViewController;
    if (vController.introView &&vController.finishedAnimation) {
        if ([vController.introView superview]) {
            [vController introAnimationEnd];
        }
    }
    
    
    NetworkErrorView *nEView = [[NetworkErrorView alloc] initWithFrame:CGRectMake(0, 0, mRect.size.width, mRect.size.height)];
    [self addSubview:nEView];
    
}


#pragma mark - UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;   //1:핫이슈데이타 2:그냥데이타rh 3:로딩뷰
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger numberOfRows = ([self.itemArray count]%2 == 0) ? (int)([self.itemArray count]/2) : (int)([self.itemArray count]/2)+1;
    
    return (section == 1) ? numberOfRows:1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return 165;
    }else if(indexPath.section == 1){
        return 146;
    }else{
        return 50;
    }
    
}

//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    
//}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //    cell.leftImage.image = cell.rightImage.image = [UIImage imageNamed:@"thumb_270254"];
    //    cell.leftTitle.text = cell.rightTitle.text = nil;
    
    if (indexPath.section == 0) {
        
        
        static NSString *CellIdentifier = @"IssueList_Head";
        ListCell *cell = (ListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.delegate = self;
        }
        cell.backgroundColor = ColorFromRGB(0x4d4d57);
        
        [cell cellOfIssueWithHotList:self.itemHeadArray andFirstTitle:nil andSecondTitle:nil];
        [cell.centerButton addTarget:self action:@selector(hotissueClick) forControlEvents:UIControlEventTouchUpInside];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    else if(indexPath.section == 1){
        
        static NSString *CellIdentifier = @"IssueList_List";
        ListCell *cell = (ListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.delegate = self;
        }
        cell.backgroundColor = ColorFromRGB(0x4d4d57);
        
        NSString *first, *second;
        
        
        
        if ((indexPath.row*2) < [self.itemArray count]) {
            
            //재사용시 기존 이미지 가림
            if (!cell.leftImage.image || cell.leftImage.tag != indexPath.row) {
                cell.leftImage.image = nil;
                [cell cellLeftIconImage:nil];
            }
            
            first = [[self.itemArray objectAtIndex:indexPath.row*2] objectForKey:@"title"];
            cell.leftImage.tag = indexPath.row;
            cell.leftButton.tag = indexPath.row*2;
            [cell.leftButton addTarget:self action:@selector(listLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            
             [appDelegate getImgDownload:[NSString stringWithFormat:@"%@%@",self.imageURL,[[self.itemArray objectAtIndex:indexPath.row*2] objectForKey:@"thumb_url"]] setImage:cell.leftImage];
            
//            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[[self.itemArray objectAtIndex:indexPath.row*2] objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
//                if (cell.leftImage.tag == indexPath.row) {
//                    
//                    cell.leftImage.image = image;
////                    cell.leftImage.alpha = 0.0f;
////                    [UIView animateWithDuration:1.0f animations:^{
////                        cell.leftImage.alpha = 1.0f;
////                    }];
//                }
//            } errorBlock:^{
//                if (cell.leftImage.tag == indexPath.row) {
//                    
//                    cell.leftImage.image = nil;
//                }
//            }];
            
            //리본아이콘
            NSString *icon = [[self.itemArray objectAtIndex:indexPath.row*2] objectForKey:@"icon"];
            if ([appDelegate checkObject:icon]) {
                NSString *imgurl = [appDelegate.iconDictionary objectForKey:icon];
                cell.leftIcon.tag = indexPath.row;
                
                [appDelegate loadAsyncImageFromURLString:imgurl imageBlock:^(UIImage *image) {
                    if (cell.leftIcon.tag == indexPath.row) {
                        
                        [cell cellLeftIconImage:image];
                    }
                } errorBlock:^{
                    
                    [cell cellLeftIconImage:nil];
                }];
            }
        }
        if ((indexPath.row*2)+1 < [self.itemArray count]) {
            
            //재사용시 기존 이미지 가림
            if (!cell.rightImage.image || cell.rightImage.tag != indexPath.row) {
                cell.rightImage.image = nil;
                [cell cellRightIconImage:nil];
            }
            
            second = [[self.itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"title"];
            //            secondURL = [NSString stringWithFormat:@"%@%@",self.imageURL,[[self.itemArray objectAtIndex:(indexPath.row*2)+1]objectForKey:@"thumb_url"]];
            cell.rightImage.tag = indexPath.row;
            cell.rightButton.tag = (indexPath.row*2)+1;
            [cell.rightButton addTarget:self action:@selector(listRightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [appDelegate getImgDownload:[NSString stringWithFormat:@"%@%@",self.imageURL,[[self.itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"thumb_url"]] setImage:cell.rightImage];
            
//            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[[self.itemArray objectAtIndex:(indexPath.row*2)+1]objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
//                
//                if (cell.rightImage.tag == indexPath.row) {
//
//                    cell.rightImage.image = image;
////                    cell.rightImage.alpha = 0.0f;
////                    [UIView animateWithDuration:1.0f animations:^{
////                        cell.rightImage.alpha = 1.0f;
////                    }];
//                    
////                    [appDelegate effectFaceoutTargetView:cell.rightImage];
//                }
//            } errorBlock:^{
//                
//                if (cell.rightImage.tag == indexPath.row) {
//                    
//                    cell.rightImage.image = nil;
//                }
//            }];
            
            //리본아이콘
            NSString *icon = [[self.itemArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"icon"];
            
            if ([appDelegate checkObject:icon]) {
                NSString *imgurl = [appDelegate.iconDictionary objectForKey:icon];
                cell.rightIcon.tag = indexPath.row;
                
                
                [appDelegate loadAsyncImageFromURLString:imgurl imageBlock:^(UIImage *image) {
                    if (cell.leftIcon.tag == indexPath.row) {
                        
                        [cell cellRightIconImage:image];
                    }
                } errorBlock:^{
                    
                    [cell cellRightIconImage:nil];
                }];
                
            }
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell cellOfIssueWithHotList:nil andFirstTitle:first andSecondTitle:second];
        
        return cell;
    }
    else{
        static NSString *CellIdentifier = @"UITableViewCell";
        UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [self makeActivityIndicatorView];
            [cell.contentView addSubview:activieiBGView];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

#pragma mark - UIScrollView Delegate
//다음페이지 이동
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    if (!duringNetwork && ([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height) {
        
        
        [self loadNextPage];
        
        currentOffsetY = scrollView.contentOffset.y;
    }else{
        [self bannerHidden:NO];
    }
}

//업데이트
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    if (!duringNetwork && scrollView.contentOffset.y < -50) {

        [self requestIssueListWithPageNumber:1];
        
    }else if (!decelerate) {
        
        [self bannerHidden:NO];
    }
    
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self bannerHidden:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

-(void)scrollOffsetChange:(id)userInfo{
    
}


#pragma mark - 상세 기사페이지로 넘어가기
#pragma mark 핫이슈에서..

-(void)hotissueClick{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    NSString *issueID = [[self.itemHeadArray objectAtIndex:self.currentHeadIndex] objectForKey:@"issue_id"];
    
    PhotoViewController *photoController = [[PhotoViewController alloc] init];
    photoController.parentClassIndex = 1;
    photoController.adCount = appDelegate.issueAdCount;
    photoController.mDelegate = self;
    photoController.issuesList = self.itemHeadArray;
    [photoController setIssueIndex:self.currentHeadIndex];
    photoController.typeHotIssue = YES;
    photoController.analyticsAction = ANA_ACT_ISSUE;
    photoController.analyticsLabelDetail = ANA_LAB_Issue_Detail;
    photoController.analyticsLabelWhole = ANA_LAB_Issue_Whole;
    [photoController requestIssueID:issueID];
    
    [viewController presentViewController:photoController animated:YES completion:nil];
//    [viewController presentModalViewController:photoController animated:YES];
    
}

#pragma mark 일반
-(void)listLeftButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearPhotoViewControllerWithIndex:button.tag];
}

-(void)listRightButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearPhotoViewControllerWithIndex:button.tag];

}

-(void)appearPhotoViewControllerWithIndex:(NSInteger)index {
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    
    NSString *issueID = [[self.itemArray objectAtIndex:index] objectForKey:@"issue_id"];
    PhotoViewController *photoController = [[PhotoViewController alloc] init];
    photoController.parentClassIndex = 1;
    photoController.adCount = appDelegate.issueAdCount;
    photoController.mDelegate = self;
    photoController.issuesList = self.itemArray;
    photoController.analyticsAction = ANA_ACT_ISSUE;
    photoController.analyticsLabelDetail = ANA_LAB_Issue_Detail;
    photoController.analyticsLabelWhole = ANA_LAB_Issue_Whole;
    [photoController setIssueIndex:index];
    [photoController requestIssueID:issueID];
    [viewController presentViewController:photoController animated:YES completion:nil];
}

#pragma mark 노티에서 넘어갈때(한가지 기사만)

-(void)appearPhotoViewControllerWithID:(NSString*)issueID {
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_ISSUE Label:ANA_LAB_Issue_Whole];
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    PhotoViewController *photoController = [[PhotoViewController alloc] init];
    photoController.parentClassIndex = 4;
    photoController.mDelegate = self;
    [photoController setIssueIndex:0];
    [photoController requestIssueID:issueID];
    [viewController presentViewController:photoController animated:YES completion:nil];
}

#pragma mark 푸쉬에서 넘어갈때(한가지 기사만)
-(void)appearPhotoViewControllerWithID:(NSString *)issueID andPushID:(NSString *)pushID{
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_ISSUE Label:ANA_LAB_Issue_Whole];
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    PhotoViewController *photoController = [[PhotoViewController alloc] init];
    photoController.parentClassIndex = 4;
    photoController.mDelegate = self;
    [photoController setIssueIndex:0];
    [photoController requestIssueID:issueID andPushID:pushID];
    
    [viewController presentViewController:photoController animated:YES completion:nil];
}


#pragma mark - 페이지

-(void)loadNextPage{
    
    if (isEnd) {
        
        [self requestIssueListWithPageNumber:currentPage];
    }else{
        //마지막페이지임
        [appDelegate alertViewWithMessage:NSLocalizedString(@"Last page", @"") andTimeInterval:2.0f];
    }
}



@end
